Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Set Interface → Set in Java

Set Interface

Set in Java

Set Interface in the Java Collections Framework

The Set interface in Java represents collections that store unique elements. It enforces that no duplicate elements can exist within a set. This interface extends the Collection interface and provides functionalities specific to maintaining unordered collections with distinct elements.

Characteristics of Set

Unordered: Elements are not maintained in any specific order. Duplicates: Not allowed. Adding a duplicate element has no effect (element isn't added). Hashing: Most implementations rely on hashing for efficient element lookups.

Common Implementations of Set

HashSet: Unordered set based on hashing. Offers fast lookups (average constant time) but doesn't maintain insertion order. TreeSet: Ordered set that maintains elements in sorted order. Useful when you need to iterate through elements in a specific order.

Methods of the Set Interface

add(E element): Attempts to add the specified element to the set. If the element is already present, the add operation has no effect. contains(Object o): Checks if the set contains the specified element. remove(Object o): Attempts to remove the specified element from the set. Returns true if the element was removed, false otherwise. isEmpty(): Checks if the set is empty. size(): Returns the number of elements in the set.

Example: Using HashSet:

Basic set example using hashset import java.util.HashSet; public class Main { public static void main(String[] args) { // Create a HashSet HashSet<String> colors = new HashSet<>(); colors.add("Red"); colors.add("Green"); colors.add("Blue"); colors.add("Red"); // Duplicate will not be added // Check if element exists if (colors.contains("Yellow")) { System.out.println("Yellow is present"); } else { System.out.println("Yellow is not present"); } // Iterate through elements (order is not guaranteed) for (String color : colors) { System.out.println(color); } } }

Output

Yellow is not present Red Blue Green
This example demonstrates adding elements, checking for existence, and iterating through a HashSet. Remember that the order of elements in the output might differ due to the unordered nature of HashSet.

Tutorials